<?php

/**
 * Pagina register.php
 * Gestisce la grafica legata alla registrazioneW
 */

require('php/inc/global.inc.php');

// istanzio un nuovo oggetto Form per la gestione del formulario di registrazione
$form = new Form("POST", "register.php");

/**
 * creo una variabile per ogni elemento nella $_POST che come nome ha la chiave dell'indice dell'array
 * è come fare $name = $_POST['name'] per ogni elemento nella $_POST ;-)
 * il vantaggio è che è più comodo da utilizzare nel formulario perché si controlla solo $name, $surname e cosi via, e non $_POST['name'] ecc..
 */
foreach ($_POST as $key => $value) {
    $$key = $value;
}


/**
 * Inizio fase di registazione
 * Quando viene premuto il bottone "Registrati" vengono effettuate una serie di operazioni e controlli sui valori inseriti
 * La registrazione ha luogo solamente quando non ci sono errori durante la registrazione, quindi quando tutti i campi inseriti
 * sono corretti e plausibili
 */
if (!$user->isLogged()) {
    $register_errors = array();

    $new_user = new User();
    if (isset($_REQUEST['register'])) {
        if (Form::validateField("name", $name)) {
            $new_user->name = $name;
        } else {
            $register_errors['reg_err_name'] = "Nome non valido!";
        }
        if (Form::validateField("surname", $surname)) {
            $new_user->surname = $surname;
        } else {
            $register_errors['reg_err_surname'] = "Cognome non valido!";
        }

        if (Form::validateField("username", $username)) {
            if (Form::validateField("username_free", $username)) {
                $new_user->username = $username;
            } else {
                $register_errors['reg_err_username'] = "L'username non &egrave; disponibile";
            }
        } else {
            $register_errors['reg_err_username'] = "Username non valido";
        }

        if (Form::validateField("email", $email)) {
            if (Form::validateField("emailFree", $email)) {
                $new_user->email = $email;
            } else {
                $register_errors['reg_err_email'] = "L'indirizzo email indicato &egrave; gi&agrave; registrato";
            }
        } else {
            $register_errors['reg_err_email'] = "Email non valida!";
        }


        if ($password == "") {
            $register_errors['reg_err_password'] = "Inserisci la password desiderata!";
        } else {
            if ($repeat_password != $password OR $repeat_password == "") {
                $register_errors['reg_err_password'] = "Le due password non corrispondono!";
            } else {
                $new_user->password = md5($password);
            }
        }

        $new_user->gender = $gender;

        if (checkdate($month, $day, $year)) {
            $new_user->date_of_birth = date("Y-m-d", mktime(0, 0, 0, $month, $day, $year));
        } else {
            $register_errors['reg_err_dateofbirth'] = "Data non valida!";
        }

        if (count($register_errors) == 0) {

            $new_user->activation_id = Util::generateActivationID();

            $registered = User::registerUser($new_user);

            if ($registered) {
                KLogger::logToDB($new_user->username. " ha effettuato la registrazione", $user->username, KLOGGER::REGISTER);
                echo "<script>window.location = 'index.php';</script>";
            } else {
                echo "<script>alert('ERRORE NELL\'INSERIMENTO')</script>";
            }

            /*
             *
             * Invio email in caso di registrazione

              if (!$resultUser) {
              echo "<script>alert('Errore nell\'inserimento dell\'utente')</script>";
              } else {
              /*
              $message = "Corpo dell'email";

              mail($user->email, "Forum - Conferma iscrizione", $message);

              $feedback_login = $user->login($user->email, $user->password);

              //echo "<script>window.location = 'index.php';</script>";

              }
             * */
        }
    }
}


/**
 * Carico gli errori in variabili distinte per una migliore gestione
 */
if (isset($register_errors)) {
    foreach ($register_errors as $key => $value) {
        $$key = $value;
    }
}


/**
 * Preparo le variabili in smarty da passare alla grafica
 */
$smarty->assign("openRegisterForm", $form->openForm());
$smarty->assign("closeRegisterForm", $form->closeForm());

$smarty->assign("label_name", $form->createLabel($lang['name']));
$smarty->assign("input_name", $form->createInput("name", "name", "text", (isset($name) ? $name : ""))); // al posto che(isset($_POST['name'])?$_POST['name']:"") grazie al foreach che ho commentato sopra
$smarty->assign("form_reg_err_name", (isset($reg_err_name) ? $reg_err_name : ""));

$smarty->assign("label_surname", $form->createLabel($lang['surname']));
$smarty->assign("input_surname", $form->createInput("surname", "surname", "text", (isset($surname) ? $surname : "")));
$smarty->assign("form_reg_err_surname", (isset($reg_err_surname) ? $reg_err_surname : ""));

$smarty->assign("label_username", $form->createLabel($lang['username']));
$smarty->assign("input_username", $form->createInput("username", "username", "text", (isset($username) ? $username : "")));
$smarty->assign("form_reg_err_username", (isset($reg_err_username) ? $reg_err_username : ""));

$smarty->assign("label_email", $form->createLabel($lang['email']));
$smarty->assign("input_email", $form->createInput("email", "email", "text", (isset($email) ? $email : "")));
$smarty->assign("form_reg_err_email", (isset($reg_err_email) ? $reg_err_email : ""));

$smarty->assign("label_password", $form->createLabel($lang['password']));
$smarty->assign("input_password", $form->createInput("password", "password", "password"));
$smarty->assign("form_reg_err_password", (isset($reg_err_password) ? $reg_err_password : ""));

$smarty->assign("label_gender", $form->createLabel($lang['gender']));
$smarty->assign("select_gender_open", $form->openSelect("gender"));
$smarty->assign("select_gender_option_m", $form->createOption("m", $lang['gender_m'], (isset($gender) && $gender == 'm' ? "selected" : "")));
$smarty->assign("select_gender_option_f", $form->createOption("f", $lang['gender_f'], (isset($gender) && $gender == 'f' ? "selected" : "")));
$smarty->assign("select_gender_close", $form->closeSelect());

$smarty->assign("label_date_of_birth", $form->createLabel($lang['date_of_birth']));
$smarty->assign("select_day_open", $form->openSelect("day"));
$smarty->assign("select_day_options", $form->createSpinner("day", (isset($day) ? $day : "")));
$smarty->assign("select_day_close", $form->closeSelect());

$smarty->assign("select_month_open", $form->openSelect("month"));
$smarty->assign("select_month_options", $form->createSpinner("month", (isset($month) ? $month : "")));
$smarty->assign("select_month_close", $form->closeSelect());

$smarty->assign("select_year_open", $form->openSelect("year"));
$smarty->assign("select_year_options", $form->createSpinner("year", (isset($year) ? $year : ""), 2012, 50));
$smarty->assign("select_year_close", $form->closeSelect());
$smarty->assign("form_reg_err_dateofbirth", (isset($reg_err_dateofbirth) ? $reg_err_dateofbirth : ""));

$smarty->assign("label_repeat_password", $form->createLabel($lang['repeat_password']));
$smarty->assign("input_repeat_password", $form->createInput("repeat_password", "repeat_password", "password"));

$smarty->assign("submit_register", $form->createInput("register", "register", "submit", $lang['register']));


// Carico l'HTML tramite smarty
$smarty->display($PAGES_URL . 'header.tpl');
$smarty->display($PAGES_URL . 'menu.tpl');
$smarty->display($PAGES_URL . 'register.tpl');
$smarty->display($PAGES_URL . 'footer.tpl');
?>
